package com.source.hotelbath.weight.listview.ptr.ptr;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;


import com.source.hotelbath.R;
import com.source.hotelbath.weight.listview.ptr.PtrDefHeader;
import com.source.hotelbath.weight.listview.ptr.PtrHeaderBase;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * 自定义属性
 * content_bkg：下拉的contentview 的背景，如果是listview 则是这是listview的背景，
 * 默认contentview 背景是透明跟随PtrLoadMoreListView的bkg
 * empty_layout：是当进入界面时界面数据位空的时候的界面
 * Created by kinglong on 15-6-4.
 */
public class PtrBase<T extends View> extends RelativeLayout implements PtrBaseInterface<T> {

    protected PtrFrameLayout mPtrFrame;
    protected PtrHeaderBase mHeader;

    protected RelativeLayout mRlContent;

    protected RelativeLayout mEmptyViewContainer;

    protected RefreshListener mRefreshListener;

    protected T mContentView;


    protected View mCheckPtrView;       //检查是否可下拉刷新的view

    protected int mContentBkgId;
    protected int mEmptyLayoutId;

    protected boolean mIsReady;

    public PtrBase(Context context) {
        super(context);
        View view= LayoutInflater.from(context).inflate(R.layout.ptr_base, null);
        addView(view);
        mPtrFrame = (PtrFrameLayout) findViewById(R.id.ptr_frame);
        mEmptyViewContainer = (RelativeLayout) findViewById(R.id.rl_empty_container);
        mRlContent = (RelativeLayout) findViewById(R.id.rl_content);
        setRefresh();
        setEmptyView(R.layout.ptr_listview_empty);
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                mIsReady = true;
            }
        });
    }

    public PtrBase(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.ptr_base, this, true);
        mPtrFrame = (PtrFrameLayout) findViewById(R.id.ptr_frame);
        mEmptyViewContainer = (RelativeLayout) findViewById(R.id.rl_empty_container);
        mRlContent = (RelativeLayout) findViewById(R.id.rl_content);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ptr);
        mContentBkgId = typedArray.getResourceId(R.styleable.ptr_content_bkg, -1);
        mEmptyLayoutId = typedArray.getResourceId(R.styleable.ptr_empty_layout, -1);
        if(mContentBkgId!=-1)
            mRlContent.setBackgroundResource(mContentBkgId);

        setRefresh();
        if (-1 != mEmptyLayoutId) {
            setEmptyView(mEmptyLayoutId);
        } else {
            setEmptyView(R.layout.ptr_listview_empty);
        }
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                mIsReady = true;
            }
        });
    }


    /**
     * 设置下拉刷新的参数，监听
     */
    private void setRefresh() {
        mHeader = new PtrDefHeader(getContext());
        mPtrFrame.setHeaderView(mHeader);
        mPtrFrame.addPtrUIHandler(mHeader);
        mPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // here check $mListView instead of $content
                if (mCheckPtrView != null) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(frame, mCheckPtrView, header);
                } else if (null != mContentView) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(frame, mContentView, header);
                } else {
                    Log.e("ptr error","you have no view to pulltorefresh");
                    return false;
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if(null!=mRefreshListener){
                    mRefreshListener.refresh();
                }else{
                    mPtrFrame.refreshComplete();
                }
            }
        });
    }

    @Override
    public <K extends PtrHeaderBase> void setHeader(K header) {
        mPtrFrame.setHeaderView(header);
        mPtrFrame.addPtrUIHandler(header);
        if (!TextUtils.isEmpty(mHeader.getLastUpdateTimeKey()))
            header.setLastUpdateTimeKey(mHeader.getLastUpdateTimeKey());
        mHeader = header;
    }

    /**
     * 设置显示上次更新的spf 对应的key，一个应用可能存在多个下拉刷新，key需要分开存储，
     * 如果不设置或者设置为空，则下拉的时候不会显示上次更新的时间
     *
     * @param value
     */
    public void setLastUpdateKey(String value) {
        mHeader.setLastUpdateTimeKey(value);
    }


    @Override
    public void autoRefresh() {
        if (!mIsReady) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    autoRefresh();
                }
            }, 200);
        }else{
            mPtrFrame.autoRefresh();
        }
    }


    @Override
    public void refreshSuccess() {
        if(mPtrFrame.isRefreshing()){
            mPtrFrame.refreshComplete();
        }
        showContentView();
    }

    @Override
    public void refreshFailure() {
        if(mPtrFrame.isRefreshing()){
            mPtrFrame.refreshComplete();
        }
    }

    @Override
    public void refreshFailure(boolean value) {
        mPtrFrame.refreshComplete();
        if (value) {
            showEmptyView();
        }
    }


    @Override
    public void setEmptyView(View view) {
        mEmptyViewContainer.removeAllViews();
        mEmptyViewContainer.addView(view);
    }

    @Override
    public void setEmptyView(int id) {
        View view = LayoutInflater.from(getContext()).inflate(id, null);
        mEmptyViewContainer.removeAllViews();
        mEmptyViewContainer.addView(view);
    }

    @Override
    public View getEmptyView() {
        if (mEmptyViewContainer.getChildCount() > 0) {
            return mEmptyViewContainer.getChildAt(0);
        } else {
            return null;
        }
    }


    @Override
    public void setRefreshView(T view) {
        if(view.getParent()!=null&&view.getParent() instanceof ViewGroup){
            ViewGroup viewGroup= (ViewGroup) view.getParent();
            viewGroup.removeView(view);
        }
        mRlContent.addView(view);
        mContentView = view;
        showEmptyView();
    }

    @Override
    public T getRefreshView() {
        return mContentView;
    }

    @Override
    public void showEmptyView() {
        mEmptyViewContainer.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
    }

    @Override
    public void showContentView() {
        mEmptyViewContainer.setVisibility(View.GONE);
        mContentView.setVisibility(View.VISIBLE);
    }

    public PtrFrameLayout getPtrFrame() {
        return mPtrFrame;
    }

    public interface RefreshListener {
        public void refresh();
    }

    public void setCheckPtrView(View checkPtrView) {
        this.mCheckPtrView = checkPtrView;
    }

    public void registListener(RefreshListener refreshListener) {
        mRefreshListener = refreshListener;
    }

    @Override
    public void disableWhenHorizontalMove(boolean value) {
        mPtrFrame.disableWhenHorizontalMove(value);
    }
}
